package net.zhengxinyun.performance.controller.indicators;


import com.sirdc.modules.core.exceptions.SystemException;
import jodd.csselly.selector.PseudoClass;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.CountryUnitIndicatorsFilter;
import net.zhengxinyun.performance.filter.CountryUnitScoreFilter;
import net.zhengxinyun.performance.filter.DepartmentFilter;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.exportService.ExportService;
import net.zhengxinyun.performance.service.indicators.CountryUnitIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryUnitScoreService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.login.UserService;
import net.zhengxinyun.performance.service.report.IndexReportService;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 县指标控制层
 *
 * @Auther: hyp
 * @Date: 2018/10/26 16:11
 */
@RestController
@RequestMapping("/countryUnitScore")
public class CountryUnitScoreController {

    private CountryUnitIndicatorsService countryUnitIndicatorsService;
    private TokenService tokenService;
    private CountryUnitScoreService countryUnitScoreService;
    private UserService userService;
    private LoginService loginService;
    private DepartmentService departmentService;
    private ExportService exportExcel;

    @Autowired
    private IndexReportService reportService;

    @Autowired
    public CountryUnitScoreController(DepartmentService departmentService, CountryUnitIndicatorsService countryUnitIndicatorsService, TokenService tokenService, UserService userService, LoginService loginService, CountryUnitScoreService countryUnitScoreService,ExportService exportExcel) {
        this.countryUnitIndicatorsService = countryUnitIndicatorsService;
        this.countryUnitScoreService = countryUnitScoreService;
        this.tokenService = tokenService;
        this.userService = userService;
        this.loginService = loginService;
        this.departmentService = departmentService;
        this.exportExcel = exportExcel;



    }

    /**
     * 分数删除
     *
     * @param param
     * @return
     */
    @PostMapping("/delete")
    public Result<String> delete(@RequestBody CountryUnitScoreParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            String str = countryUnitScoreService.delete(param.countryUnitScoreEntity);
            if (!"删除成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            } else {
                return ResultUtils.getSuccessResults();
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 分数修改
     *
     * @param param
     * @return
     */
    @PostMapping("/update")
    public Result<String> update(@RequestBody CountryUnitScoreParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            int i = countryUnitScoreService.update(param.countryUnitScoreEntity);
            if (i == 1) {
                return ResultUtils.getSuccessResults();
            } else {
                return ResultUtils.getResults(Result.Status.ERROR, "更新失败，请联系管理员");
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 分数添加
     *
     * @param param
     * @return
     */
    @PostMapping("/insert")
    public Result<String> insert(@RequestBody CountryUnitScoreParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            CountryUnitIndicatorsFilter filter = new CountryUnitIndicatorsFilter();
            if (param.countryUnitScoreEntity != null) {
                CountryUnitScoreEntity countryUnitScoreEntity = param.countryUnitScoreEntity;
                //将audit状态改为已填写1
                countryUnitScoreEntity.setAudit("1");

                String responsibilityId = countryUnitScoreEntity.getResponsibilityId();
                DepartmentFilter departmentFilter = new DepartmentFilter();
                departmentFilter.setDepartcode(responsibilityId);
                List<DepartmentFilter> filters = departmentService.query(departmentFilter);
                if (filters.size() != 1) {
                    return ResultUtils.getResults(Result.Status.ERROR, "添加失败,请联系管理员");
                }
                countryUnitScoreEntity.setDepartment(filters.get(0).getDepartment());

                int i = countryUnitScoreService.insert(countryUnitScoreEntity);
                if (i != 0) {
                    return ResultUtils.getSuccessResults();
                } else {
                    return ResultUtils.getResults(Result.Status.ERROR, "添加失败，请联系管理员");
                }
            } else if (param.list != null) {
                List<CountryUnitScoreEntity> list = param.list;
                /*for (CountryUnitScoreEntity unitScoreEntity : list) {
                    unitScoreEntity.setAudit("1");
                }*/
                String str = countryUnitScoreService.insertByBatch(list);
                if (!"批量插入成功".equals(str)) {
                    return ResultUtils.getResults(Result.Status.ERROR, "添加失败，请联系管理员");
                }
                return ResultUtils.getSuccessResults();
            }
            return ResultUtils.getResults(Result.Status.ERROR);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 查询分数
     *
     * @param param
     * @return
     */
    @PostMapping("/query")
    public Result<HashMap<String, Object>> query(@RequestBody CountryUnitScoreParam param, HttpServletRequest request) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if (param.countryUnitScoreFilter.getPageSize() == 0) {
                param.countryUnitScoreFilter.setPageSize(10);
            }
            String currentyear = null;
            if(StringUtils.isBlank(param.countryUnitScoreFilter.getDateTime()))
            {
                currentyear = (String) request.getSession().getAttribute("currentYear");
                if(currentyear==null)
                {
                    return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
                }

            }

            HashMap<String, Object> map = new HashMap<>();
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
        /*
            不需要按照牵头单位来县直， 按照勾选的指标去筛选
            if (!"admin".equals(userEntity.getUserPermissions())) {
                param.countryUnitScoreFilter.setLeadUnit(userEntity.getDepartcode());
            }*/
            if (StringUtils.isBlank(param.countryUnitScoreFilter.getDateTime())) {
                param.countryUnitScoreFilter.setDateTime(DateUtils.getLastMonth(currentyear));
            }

            List<CountryUnitScoreFilter>  list = countryUnitScoreService.queryScoreHomeDate(param.countryUnitScoreFilter,userEntity);
            if (list.size() == 0){
                param.countryUnitScoreFilter.setPageNumber(param.countryUnitScoreFilter.getPageNumber()-1);
                list = countryUnitScoreService.queryScoreHomeDate(param.countryUnitScoreFilter,userEntity);
            }
            Integer pageTotal = countryUnitScoreService.queryForCount(param.countryUnitScoreFilter);
            map.put("pageTotal",pageTotal);
            map.put("list",list);//根据条件查询集合
   /*
        //返回所有县直属单位
            List<DepartmentEntity> unitList = countryUnitScoreService.queryCountryUnit();

            for (DepartmentEntity entity : unitList) {
                param.countryUnitScoreFilter.setResponsibilityId(entity.getDepartcode());
                List<Map<String, Object>> list = countryUnitScoreService.queryScoreList(param.countryUnitScoreFilter);
                if (list.size() == 0) {
                    param.countryUnitScoreFilter.setPageNumber(param.countryUnitScoreFilter.getPageNumber() - 1);
                    list = countryUnitScoreService.queryScoreList(param.countryUnitScoreFilter);
                    HashMap<String, List> hashMap = new HashMap<>();
                    hashMap.put(entity.getDepartcode(),list);
                    map.put("score", hashMap);
                }
            }
            map.put("unitList", unitList);
  *//*
            List<Map<String, Object>> list = countryUnitIndicatorsService.queryScoreList(param.countryUnitIndicatorsFilter);
            if (list.size() == 0) {
                param.countryUnitIndicatorsFilter.setPageNumber(param.countryUnitIndicatorsFilter.getPageNumber() - 1);
                list = countryUnitIndicatorsService.queryScoreList(param.countryUnitIndicatorsFilter);
            }*//*

            //返回所有指标
            List<Map<Integer, String>> indicators = countryUnitScoreService.queryIndicators();
            map.put("indicators", indicators);
         *//*   //
            List<Map<String, Object>> list = countryUnitScoreService.queryScoreList(param.countryUnitScoreFilter);
            if (list.size() == 0) {
                param.countryUnitScoreFilter.setPageNumber(param.countryUnitScoreFilter.getPageNumber() - 1);
                list = countryUnitScoreService.queryScoreList(param.countryUnitScoreFilter);
            }*//*
            int pageTotal=countryUnitScoreService.countScore(param.countryUnitScoreFilter);
            map.put("pageTotal", pageTotal);
//            map.put("list", list);//根据条件查询集合*/
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }


    /**
     * excel导入县直单位分数
     */
    @PostMapping("/importUnitScore")
    public  Result<String> importExcel(@RequestBody CountryUnitScoreParam param){
        UserEntity user = loginService.getUserByToken(param.tokenEntity);
       List<CountryUnitScoreEntity> list  =  param.countryUnitScoreFilter.getListScore();

        String msg =countryUnitScoreService.saveImportUnitScore(list,param.countryUnitScoreFilter.getId());
        if(!"ok".equals(msg))
        {
            return ResultUtils.getResults(Result.Status.ERROR,msg);
        }
        reportService.saveReport(user,3,param.countryUnitScoreFilter.getId(),DateUtils.getLastMonth());

        return ResultUtils.getSuccessResults();
    }

    @PostMapping("/afterimport")
    public Result<HashMap<String,Object>> afterimport(@RequestBody CountryUnitScoreParam param)
    {
        HashMap<String, Object> map = new HashMap<>();
        param.countryUnitScoreFilter.setDateTime(DateUtils.getCurrentMonth());
        param.countryUnitScoreFilter.setIndexId(param.countryUnitScoreFilter.getId().toString());
        List<HashMap<String, Object>> list = countryUnitScoreService.queryAllData(param.countryUnitScoreFilter);
        if (list.size() == 0){
            param.countryUnitScoreFilter.setPageNumber(param.countryUnitScoreFilter.getPageNumber()-1);
            list = countryUnitScoreService.queryAllData(param.countryUnitScoreFilter);
        }
        Integer pageTotal = countryUnitScoreService.countScore(param.countryUnitScoreFilter);
        map.put("pageTotal",pageTotal);
        map.put("list",list);//根据条件查询集合
        return  ResultUtils.getSuccessResults(map);


    }

    /**
     * 导出指标完成情况
     * @param response
     */
    @GetMapping("/exportExcelMould")
    public void  exportExcel(HttpServletResponse response)
    {
        HSSFWorkbook wb= exportExcel.getCountyDataMould();
        HSSFSheet sheet = wb.getSheetAt(0);
        int rownum = sheet.getLastRowNum();
        if (rownum == 0) {
            throw new SystemException("没有数据");
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            String filename = "县直单位指标考核数据模板.xls";
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            wb.write(out);
        } catch (Exception e) {

        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

class CountryUnitScoreParam {
    public CountryUnitScoreEntity countryUnitScoreEntity;
    public CountryUnitScoreFilter countryUnitScoreFilter;
    public CountryUnitIndicatorsFilter countryUnitIndicatorsFilter;
    public List<CountryUnitScoreEntity> list;
    public TokenEntity tokenEntity;
    public String dateTime;
    public ExportService exportExcel;
}
